package com.pillpoppers.pillbox;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.pillpoppers.pillbox.MainFragmentActivity.addListener;


public class ContactsFragment extends ListFragment implements addListener {

	private ContactListAdapter adapter;
	
	ArrayList<String> name; 
	ArrayList<String> phone;
		
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_contacts, container, false);
		
		((MainFragmentActivity)getActivity()).setaddListener(this);
		
		SharedPreferences sharedPref = getActivity().getSharedPreferences(getString(R.string.contact_ids_key), 
				Context.MODE_PRIVATE);
		//
		String ids = sharedPref.getString(getString(R.string.contact_ids_key), "");
		
		ArrayList<String> list = new ArrayList<String>();
		StringTokenizer tokens = new StringTokenizer(ids);
		while(tokens.hasMoreTokens()){
			list.add(tokens.nextToken());
		}
		
		 name = new ArrayList<String>();
		 phone = new ArrayList<String>();
		
		
		
		Iterator<String> it = list.iterator();
		
		while(it.hasNext()) {
			
			String findId = it.next();
			String [] projection = new String [] {ContactsContract.Contacts.DISPLAY_NAME, 
					ContactsContract.CommonDataKinds.Phone.NUMBER, 
					ContactsContract.CommonDataKinds.Organization.TITLE}  ;
		
			String where = ContactsContract.Data.CONTACT_ID + 
					" = " + findId + " AND " + 
					ContactsContract.Data.MIMETYPE + " = '" +
					ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + 
					"'";
			
			Cursor cursor = getActivity().getContentResolver().query(ContactsContract.Data.CONTENT_URI, projection, where, null, null);
			
			int nameIdx = cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME);
			int phoneIdx =  cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER);
			
			
			while(cursor.moveToNext()){
				name.add(cursor.getString(nameIdx));
				phone.add(cursor.getString(phoneIdx));
			}//nested while
			cursor.close();
		}//while
		
		adapter = new ContactListAdapter(this, name, phone, list); 
		setListAdapter(adapter);
		
		return view;
	}
	
	
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		final String number = (String) ((ContactListAdapter) l.getAdapter()).getPhone(position);
		final String name = (String) ((ContactListAdapter) l.getAdapter()).getName(position);
		final String contactID = (String) ((ContactListAdapter) l.getAdapter()).getId(position);
		final int pos = position;
		String message = "Contact options";
		String button1 = "Call";
		String button2 = "Delete";
		
		AlertDialog.Builder ad = new AlertDialog.Builder(getActivity());
		ad.setMessage(message);
		
		ad.setPositiveButton(button1, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(Intent.ACTION_CALL);
				intent.setData(Uri.parse("tel:" + number));
				startActivity(intent);
			}
		});
		
		ad.setNegativeButton(button2, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				deleteContact(contactID, pos);
			}
		})
		.create()
		.show();
	}
	
	public static int PICK_CONTACT = 0;
	public static int NEW_CONTACT = 1;
		
	@Override
	public void addContact() {
		
		// TODO Auto-generated method stub
		String[] contactOptions = {"Create contact", "Add from existing contacts"};
		AlertDialog.Builder contactBuilder = new AlertDialog.Builder(getActivity());
		contactBuilder.setTitle("Contact options");
		
		contactBuilder.setItems(contactOptions, new DialogInterface.OnClickListener () {
			public void onClick(DialogInterface dialog, int choice) {
				if (choice == 0) {
					 Intent newIntent = new Intent(ContactsContract.Intents.Insert.ACTION, 
								ContactsContract.Contacts.CONTENT_URI);
					 startActivity(newIntent);
				} else if (choice == 1) {
					Intent intent = new Intent(Intent.ACTION_PICK,
							ContactsContract.Contacts.CONTENT_URI);
					
					startActivityForResult(intent, PICK_CONTACT);
				}
			}
		})
		.create()
		.show();
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == PICK_CONTACT) {
			if (resultCode == Activity.RESULT_OK) {
                Uri contact = data.getData();
                Cursor cursor = getActivity().getContentResolver().query(contact, null, null, null, null);
                cursor.moveToFirst();
                
                String contactID = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                                             
                cursor.close();  
                contactListId(contactID);
			}
					
		} 
		
	}//method
	
	public void contactListId(String contactID) {
		SharedPreferences sharedPref = getActivity().getSharedPreferences(getString(R.string.contact_ids_key), 
				Context.MODE_PRIVATE);
		
		String ids = sharedPref.getString(getString(R.string.contact_ids_key), "");
		Log.d("IDS", ids);
		ids = " " + ids + contactID + " ";
		
		SharedPreferences.Editor editor = sharedPref.edit();
		editor.putString(getString(R.string.contact_ids_key), ids);
		editor.commit();
		
		String [] projection = new String [] {ContactsContract.Contacts.DISPLAY_NAME, 
				ContactsContract.CommonDataKinds.Phone.NUMBER, 
				ContactsContract.CommonDataKinds.Organization.TITLE}  ;
	
		String where = ContactsContract.Data.CONTACT_ID + 
				" = " + contactID + " AND " + 
				ContactsContract.Data.MIMETYPE + " = '" +
				ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + 
				"'";
		
		Cursor cursor = getActivity().getContentResolver().query(ContactsContract.Data.CONTENT_URI, projection, where, null, null);
		
		int nameIdx = cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME);
		int phoneIdx =  cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER);
		
		
		while(cursor.moveToNext()){
			name.add(cursor.getString(nameIdx));
			phone.add(cursor.getString(phoneIdx));
		}//nested while
		cursor.close();
		adapter.notifyDataSetChanged();
		//
	}
	
	public void deleteContact(String contactID, int position){
		SharedPreferences sharedPref = getActivity().getSharedPreferences(getString(R.string.contact_ids_key), 
				Context.MODE_PRIVATE);
		
		String ids = sharedPref.getString(getString(R.string.contact_ids_key), "");
		Log.d("IDS before", ids);
		String del = ids.replace(" " + contactID + " ", " ");
		Log.d("IDS after", del);
		
		SharedPreferences.Editor editor = sharedPref.edit();
		editor.putString(getString(R.string.contact_ids_key), del);
		editor.commit();
		name.remove(position);
		phone.remove(position);
		adapter.notifyDataSetChanged();
	}

}//class
	
	



